import {request} from './axios-config'
import axios from 'axios'

// const VUE_APP_API_URL = process.env.VUE_APP_API_URL;
const OSS_DIR = "hzcgzf"; // oss文件目录
const URL = `oss`; // 后台代理路径
// const UPLOAD_URL = 'oss/api/uploadApp'
const api = "umale-maintenance-web";

/**
 * 全局唯一标识符 UUID
 * @param { Number } len 长度
 * @param { Number } radix  基数
 */

function uuid(len, radix) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  let uuid = [];
  radix = radix || chars.length;
  if (len) {
    for (let i = 0; i < len; i++) {
      uuid[i] = chars[0 | Math.random() * radix]
    }
  } else {
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';
    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        const r = 0 | Math.random() * 16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

export async function uploadFile({
  dir = OSS_DIR,
  signatureObj = null,
  file = {},
  fileName = '',
  cancelToken = null,
  attributes = {},
  onUploadProgress = function() {},
  onDownloadProgress = function() {}
}) {
  if (!signatureObj) {
    const signatureRes = await getSignature(dir);
    signatureObj = signatureRes.data;
  }

  const formData = new FormData();
  const fileType = file.name.split(".").pop();

  const key = `${signatureObj.dir}/${uuid()}.${fileType}`;
  const fileUrl = `/${URL}/${key}`;

  formData.append("key", key); // key为上传到oss后的文件名
  formData.append("policy", signatureObj.policy);
  formData.append("OSSAccessKeyId", signatureObj.accessId);
  formData.append("success_action_status", "200");
  formData.append("signature", signatureObj.signature);
  formData.append("file", file.raw || file);
  formData.append("name", file.name);
  formData.append("fileName", fileName);

  try {
    await axios({
      url: `/oss`,
      method: "POST",
      data: formData,
      headers: {
        "accesstoken": "d050c45f-f202-4c53-b83d-1b430dbf964b",
        "Content-Type": "multipart/form-data"
      },
      timeout: 0,
      onUploadProgress: function(progressEvent) {
        onUploadProgress(progressEvent, fileUrl);
      },
      onDownloadProgress: function(progressEvent) {
        onDownloadProgress(progressEvent, fileUrl);
      },
      cancelToken: cancelToken
    });

    return Promise.resolve({
      ...attributes,
      name: key,
      url: fileUrl,
      fileName: fileName
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 多文件上传
 * @param { [Array|Object] } files
 * @param { String } dir
 */
export async function uploadFiles(files = [], dir = OSS_DIR) {
  if (!files) {
    return Promise.resolve([]);
  }

  if (files.length === 0) {
    return Promise.resolve([]);
  }

  if (Object.prototype.toString.call(files) === "[object Object]") {
    files = [files];
  }

  if (Object.prototype.toString.call(files) !== "[object Array]") {
    return Promise.resolve([]);
  }

  const signatureRes = await getSignature(dir);

  if (signatureRes.code !== 0) {
    return Promise.reject(signatureRes.message);
  }

  const promiseAll = [];

  for (let i = 0, l = files.length; i < l; i++) {
    const filesItem = files[i];
    promiseAll.push(
      uploadFile({
        fileName: filesItem.name,
        signatureObj: signatureRes.data,
        file: filesItem.file || filesItem,
        cancelToken: filesItem.cancelToken || null,
        attributes: filesItem.attributes || {},
        onUploadProgress: filesItem.onUploadProgress || function() {},
        onDownloadProgress: filesItem.onDownloadProgress || function() {}
      })
    );
  }

  const res = await Promise.all(promiseAll);
  return Promise.resolve(res);
}

/**
 * 获取签名
 */
export function getSignature(dir) {
  return request({
    url: `${api}/${URL}/api/authorize`,
    method: "POST",
    data: {
      dir: dir || OSS_DIR
    }
  });
}